package gov.mogaha.ntis.cmm.mob;

import gov.mogaha.ntis.cmm.mob.adapter.CmmMobSidCnAdpater;
import gov.mogaha.ntis.cmm.mob.baseactivity.BaseActivity;
import gov.mogaha.ntis.cmm.mob.servlet.CmmMobServlet;
import gov.mogaha.ntis.cmm.mob.servlet.CmmMobServletHandler;
import gov.mogaha.ntis.cmm.mob.servlet.CmmMobServlet.DataSet;
import gov.mogaha.ntis.cmm.mob.servlet.CmmMobServletHandler.HttpResult;
import gov.mogaha.ntis.cmm.mob.util.Toaster;
import gov.mogaha.ntis.cmm.mob.view.SelectButtonView;
import gov.mogaha.ntis.cmm.mob.view.TitleView;
import gov.mogaha.ntis.cmm.mob.dto.CmmMobApvCnDto;
import gov.mogaha.ntis.cmm.mob.dto.CmmMobSidCnDto;

import java.util.ArrayList;
import java.util.Hashtable;

import wire.proto.Binding;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

public class CmmMobSidCn extends BaseActivity implements View.OnClickListener, AdapterView.OnItemClickListener, OnEditorActionListener {

	public static String upmuTag = "CmmMobSidCn";
	public static String widlUrl = "mobile/RTP_MOB_CMM";
	public static String actionName = "selectCmmMobSidCn";
	
	
	//성명입력
	private EditText nameEdit;
	//주민등록번호 앞자리 입력
	private EditText sidEdit1;
	//주민등록번호 뒷자리 입력
	private EditText sidEdit2;
	
	private SelectButtonView apvYnCheck;

	//주민정보 총갯수
	private TextView listCountText;
	//주민정보리스
	private ListView srchList;
	
	private CmmMobSidCnAdpater phmMobSidCnAdpater;
	private final ArrayList<CmmMobSidCnDto> srchDataList = new ArrayList<CmmMobSidCnDto>(); 
	
	private String dispoRaiseWrkCode;
	private String upchCobCode;
	private String sidString;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.cmmmobsidcn);
		
		savedInstanceState = this.getIntent().getExtras();
		
		if(savedInstanceState != null) {
			this.dispoRaiseWrkCode = savedInstanceState.getString("dispo_raise_wrk_code");
			this.upchCobCode = savedInstanceState.getString("upch_cob_code");
		}
		
		TitleView titleView = (TitleView) findViewById(R.id.title_view);
		titleView.setTitle("주민정보 검색");
		titleView.setBackgroundImage(R.drawable.titlebarsub);
		
		this.nameEdit = (EditText)findViewById(R.id.name_edit);
		this.sidEdit1 = (EditText)findViewById(R.id.sid_edit1);
		this.sidEdit1.addTextChangedListener(new TextWatcher() {  
	        
	        @Override  
	        public void onTextChanged(CharSequence s, int start, int before, int count) {
	        	//주민등록번호 앞자리가 6자리 입력되었을 시 입력포커스 이동
	        	if(s.toString().length() == 6) { 
	        		sidEdit2.requestFocus();
	        	}
	        }  
	          
	        @Override  
	        public void beforeTextChanged(CharSequence s, int start, int count,  int after) {
	        	return;
	        }

			@Override
			public void afterTextChanged(Editable arg0) {
	        	return;
	        }
	    });  
		this.sidEdit2 = (EditText)findViewById(R.id.sid_edit2);
		this.sidEdit2.addTextChangedListener(new TextWatcher() {  
	        
	        @Override  
	        public void onTextChanged(CharSequence s, int start, int before, int count) {
	        	//주민등록번호 뒷자리 성별 한자리를 제외한 나머지 글자 암호화 
	        	if(s.toString().length() <= 1) {
	        		sidString = s.toString();
	        	} else {
	        		if(sidString.length() != s.toString().length()) {
	        			if(sidString.length() < s.toString().length()) {
	        				sidString += s.toString().substring(s.toString().length()-1);
	        				String tmpString = "";
	        				for(int i = 0; i < s.toString().length()-1; i++) {
	        					tmpString += "*";
	        				}
	        				sidEdit2.setText(sidString.substring(0, 1)+tmpString);
	        				sidEdit2.setSelection(sidEdit2.length());
	        			} else {
	        				sidString = sidString.substring(0, s.toString().length()-1);
	        			}
	        		}
	        	}
	        }  
	          
	        @Override  
	        public void beforeTextChanged(CharSequence s, int start, int count,  int after) {
	        	return;
	        }

			@Override
			public void afterTextChanged(Editable arg0) {
	        	return;
	        } 
	    });
		this.apvYnCheck = (SelectButtonView)findViewById(R.id.apv_yn_check);
		this.apvYnCheck.setLeftText("예");
		this.apvYnCheck.setRightText("아니오");
		
		Button srchBtn = (Button)findViewById(R.id.srch_btn);
		srchBtn.setOnClickListener(this);
		Button cancelBtn = (Button)findViewById(R.id.cancel_btn);
		cancelBtn.setOnClickListener(this);
		
		this.listCountText = (TextView)findViewById(R.id.list_count_text);
		this.srchList = (ListView) findViewById(R.id.srch_list);
		this.srchList.setOnItemClickListener(this);
		
		//데이터 중복 생성 방지
		nameEdit.setOnEditorActionListener(this);
		sidEdit1.setOnEditorActionListener(this);
		sidEdit2.setOnEditorActionListener(this);
	}
	
	//데이터 조회
	private void getSrchDataList() {
		
		if(this.nameEdit.getText().toString().length() == 0) {
			showMsg(R.string.name_input);
			return;
		}
		if(this.sidEdit1.getText().toString().length()+this.sidString.length() == 0) {
			showMsg(R.string.ssn_input);
			return;
		}
		Binding inputs = new Binding();
		
		inputs.put("dispo_raise_wrk_code", dispoRaiseWrkCode); 
		inputs.put("upch_cob_code", this.upchCobCode);
		inputs.put("resi_orgz_nm", this.nameEdit.getText().toString());
		inputs.put("sid", this.sidEdit1.getText().toString()+this.sidString);
		if(this.apvYnCheck.getValue() == 1) {
			inputs.put("apv_yn", "Y");
		} else {
			inputs.put("apv_yn", "N");
		}
		
		//통신핸들러 선언
		CmmMobServletHandler handler = new CmmMobServletHandler(this);
		
		CmmMobServlet httpThread = new CmmMobServlet(this, widlUrl, upmuTag, actionName, 
				handler.getHandler(new HttpResult() {
					@Override
					public void httpCallback(DataSet data) {
						ArrayList<Hashtable<String, String>> srchData = new ArrayList<Hashtable<String, String>>();
						
						srchData = data.getHashData();
						
						srchDataList.clear();
						
						for(Hashtable<String, String> tmp : srchData) {
							CmmMobSidCnDto dto = new CmmMobSidCnDto();
							
							dto.mTrgtNm = tmp.get("trgt_nm");
							dto.mTrgtSid = tmp.get("trgt_sid");
							dto.mConvertSid = tmp.get("convert_sid");
							dto.mTrgtSidSno = tmp.get("trgt_sid_sno");
							dto.mTrgtTelno = tmp.get("trgt_telno");
							dto.mTrgtHpno = tmp.get("trgt_hpno");
							dto.mTrgtAdmdngCode = tmp.get("trgt_admdng_code");
							dto.mTrgtRegnCode = tmp.get("trgt_regn_code");
							dto.mTrgtSan = tmp.get("trgt_san");
							dto.mTrgtBunji = tmp.get("trgt_bunji");
							dto.mTrgtHo = tmp.get("trgt_ho");
							dto.mTrgtSpecAddr = tmp.get("trgt_spec_addr");
							dto.mTrgtSpecDng = tmp.get("trgt_spec_dng");
							dto.mTrgtSpecHo = tmp.get("trgt_spec_ho");
							dto.mTrgtTong = tmp.get("trgt_tong");
							dto.mTrgtBan = tmp.get("trgt_ban");
							dto.mTrgtAddr = tmp.get("trgt_addr");
							
							dto.mTgtApvNo = tmp.get("tgt_apv_no");
							dto.mUpchNm = tmp.get("upch_nm");
							dto.mUpchTelno = tmp.get("upch_telno");
							dto.mUpchAdmdngCode = tmp.get("upch_admdng_code");
							dto.mUpchRegnCode = tmp.get("upch_regn_code");
							dto.mUpchSan = tmp.get("upch_san");
							dto.mUpchBunji = tmp.get("upch_bunji");
							dto.mUpchHo = tmp.get("upch_ho");
							dto.mUpchSpecAddr = tmp.get("upch_spec_addr");
							dto.mUpchSpecDng = tmp.get("upch_spec_dng");
							dto.mUpchSpecHo = tmp.get("upch_spec_ho");
							dto.mUpchTong = tmp.get("upch_tong");
							dto.mUpchBan = tmp.get("upch_ban");
							dto.mUpchAddr = tmp.get("upch_addr");
							
							srchDataList.add(dto);
						}
						
						listCountText.setText("총 "+srchDataList.size()+"건의 검색결과");
						
						if(srchDataList.size() == 0) {
							Toaster.showMsg(CmmMobSidCn.this, R.string.no_data_trgt);
							
						} else {
							phmMobSidCnAdpater = new CmmMobSidCnAdpater(CmmMobSidCn.this, srchDataList);
							srchList.setAdapter(phmMobSidCnAdpater);
							
							nameEdit.setText("");
							sidEdit1.setText("");
							sidEdit2.setText("");
							sidString = "";
						}
					}
				}), 
				inputs);
		httpThread.start();
	}
	
	
	@Override
	public void onClick(View v) {
		InputMethodManager inputMethodManager = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
		
		switch(v.getId()) {
			case R.id.srch_btn:
				if(nameEdit.length() == 0) {
					Toaster.showMsg(CmmMobSidCn.this, R.string.name_input);
					return;
				} else if(sidEdit1.length() == 0 || sidEdit1.length() < 6) {
					Toaster.showMsg(CmmMobSidCn.this, R.string.ssn_input);
					return;
				} else if(sidEdit2.length() == 0 || sidEdit2.length() < 7) {
					Toaster.showMsg(CmmMobSidCn.this, R.string.ssn_input);
					return;
				}
				
				inputMethodManager.hideSoftInputFromWindow(this.sidEdit2.getWindowToken(), 0);
				this.getSrchDataList();
				
				break;
			case R.id.cancel_btn:
				inputMethodManager.hideSoftInputFromWindow(this.sidEdit2.getWindowToken(), 0);
				Intent intent = getIntent();
				this.setResult(Activity.RESULT_CANCELED, intent);
				this.finish();
				this.overridePendingTransition(0, 0);
				break;
			default:
				break;
		}
	}
	
	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		
		CmmMobSidCnDto sidData = srchDataList.get(position);
		CmmMobApvCnDto apvData = new CmmMobApvCnDto();
		
		if(sidData.mTgtApvNo.length() > 0) {
			apvData.mTgtApvNo = sidData.mTgtApvNo;
			apvData.mUpchNm = sidData.mUpchNm;
			apvData.mUpchTelno = sidData.mUpchTelno;
			apvData.mUpchAdmdngCode = sidData.mUpchAdmdngCode;
			apvData.mUpchRegnCode = sidData.mUpchRegnCode;
			apvData.mUpchSan = sidData.mUpchSan;
			apvData.mUpchBunji = sidData.mUpchBunji;
			apvData.mUpchHo = sidData.mUpchHo;
			apvData.mUpchSpecAddr = sidData.mUpchSpecAddr;
			apvData.mUpchSpecDng = sidData.mUpchSpecDng;
			apvData.mUpchSpecHo = sidData.mUpchSpecHo;
			apvData.mUpchTong = sidData.mUpchTong;
			apvData.mUpchBan = sidData.mUpchBan;
			apvData.mUpchAddr = sidData.mUpchAddr;
		}
		
		Intent intent = new Intent();
		intent.putExtra("sid_cn", sidData);
		intent.putExtra("apv_cn", apvData);
		this.setResult(Activity.RESULT_OK, intent);
		this.finish();
		this.overridePendingTransition(0, 0);
	}

	//EditText의 내용이 변경되었는지 여부를 확인하는 리스너
	@Override
	public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
		return false;
	}
}
